package com.yupi.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.exception.BusinessException;
import com.yupi.usercenter.mapper.TeamMapper;
import com.yupi.usercenter.model.domain.Team;
import com.yupi.usercenter.model.domain.TeamQuery;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.model.domain.UserTeam;
import com.yupi.usercenter.model.enums.TeamStatusEnum;
import com.yupi.usercenter.model.request.TeamJoinRequest;
import com.yupi.usercenter.model.request.TeamQuitRequest;
import com.yupi.usercenter.model.request.TeamUpdateRequest;
import com.yupi.usercenter.model.vo.TeamUserVO;
import com.yupi.usercenter.model.vo.UserVO;
import com.yupi.usercenter.service.TeamService;
import com.yupi.usercenter.service.UserService;
import com.yupi.usercenter.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
* @author 24125
* @description 针对表【team(队伍)】的数据库操作Service实现
* @createDate 2024-03-15 12:19:26
*/
@Service
@Slf4j
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team>
    implements TeamService {
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private UserService userService;
    @Resource
    private RedissonClient redissonClient;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public long addTeam(Team team, User loginUser){
        //1、请求参数是否为空
        if (team==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2、是否登录，未登录不允许创建
        if (loginUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        final long userId=loginUser.getId();
        //3、验证信息
            //1、队伍人数>1且<=20
        int maxNum= Optional.ofNullable(team.getMaxNum()).orElse(0);
        if (maxNum<1 || maxNum>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍人数不满足要求");
        }
            //2、队伍标题<=20
        String name=team.getName();
        if (StringUtils.isBlank(name) || name.length()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍标题不满足要求");
        }
            //3、描述<=512
        String description=team.getDescription();
        if (StringUtils.isNotBlank(description)&&description.length()>512){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"队伍描述过长");
        }
            //4、status是否公开(int)不传默认为0(公开)
        int status=Optional.ofNullable(team.getStatus()).orElse(0);
        TeamStatusEnum statusEnum=TeamStatusEnum.getEnumByValue(status);
        if (statusEnum==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍状态不满足要求");
        }
            //5、如果status是加密状态,一定要有密码,且密码<=32
        String password=team.getPassword();
        if (TeamStatusEnum.SECRET.equals(statusEnum)){
            if (StringUtils.isBlank(password)||password.length()>32){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码设置不正确");
            }
        }
            //6、超出时间>当前时间
        Date expireTime=team.getExpireTime();
        if (new Date().after(expireTime)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"超时时间 > 当前时间");
        }
            //7、校验用户最多创建5个队伍
            //togo有bug,可能同时创建100队伍
        QueryWrapper<Team> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        long hasTeamNum=this.count(queryWrapper);
        if (hasTeamNum>=5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户最多创建5个队伍");
        }
        //4、插入队伍信息到队伍表
        team.setId(null);
        team.setUserId(userId);
        boolean result=this.save(team);
        Long teamId=team.getId();
        //事务回滚机制
        if (!result||teamId==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"创建队伍失败");
        }
        //5、输入用户=>用户关系到关系表
        UserTeam userTeam=new UserTeam();
        userTeam.setUserId(userId);
        userTeam.setTeamId(teamId);
        userTeam.setJoinTime(new Date());
        result= userTeamService.save(userTeam);
        if (!result){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"创建队伍失败");
        }
        return teamId;

    }

    @Override
    public List<TeamUserVO> listTeams(TeamQuery teamQuery, boolean isAdmin) {
        QueryWrapper<Team> queryWrapper=new QueryWrapper<>();
        //组合查询条件
        if (queryWrapper!=null){
            Long id=teamQuery.getId();
            if (id!=null&&id>0){
                queryWrapper.eq("id",id);
            }
            List<Long> idList=teamQuery.getIdList();
            if (CollectionUtils.isNotEmpty(idList)){
                queryWrapper.in("id",idList);
            }
            String searchText=teamQuery.getSearchText();
            if (StringUtils.isNotBlank(searchText)){
                queryWrapper.and(qw ->qw.like("name",searchText).or().like("description",searchText));
            }
            String name=teamQuery.getName();
            if (StringUtils.isNotBlank(name)){
                queryWrapper.like("name",name);
            }
            String description=teamQuery.getDescription();
            if (StringUtils.isNotBlank(description)){
                queryWrapper.like("description",description);
            }
            Integer maxNum=teamQuery.getMaxNum();
            //查询最大人数相等的
            if (maxNum!=null&&maxNum>0){
                queryWrapper.eq("maxNum",maxNum);
            }
            Long userId=teamQuery.getUserId();
            //根据创建人来查询
            if (userId!=null&&userId>0){
                queryWrapper.eq("userId",userId);
            }
            //根据状态来查询
            Integer status=teamQuery.getStatus();
            TeamStatusEnum statusEnum=TeamStatusEnum.getEnumByValue(status);
            if (statusEnum==null){
                statusEnum=TeamStatusEnum.PUBLIC;
            }
            if (!isAdmin && statusEnum.equals(TeamStatusEnum.PRIVATE)){
                throw new BusinessException(ErrorCode.NO_AUTH);
            }
            queryWrapper.eq("status",statusEnum.getValue());
        }
        //不展示已过期的队伍
        queryWrapper.and(qw -> qw.gt("expireTime", new Date()).or().isNull("expireTime"));
        List<Team> teamList=this.list(queryWrapper);
        if (CollectionUtils.isEmpty(teamList)){
            return new ArrayList<>();
        }
        List<TeamUserVO> teamUserVOList=new ArrayList<>();
        //关联创建人的用户信息
        for(Team team:teamList){
            Long userId=team.getUserId();
            if (userId==null){
                continue;
            }
            User user=userService.getById(userId);
            TeamUserVO teamUserVO=new TeamUserVO();
            BeanUtils.copyProperties(team,teamUserVO);
            //脱敏用户
            if(user!=null){
                UserVO userVO=new UserVO();
                BeanUtils.copyProperties(user,userVO);
                teamUserVO.setCreateUser(userVO);
            }
            teamUserVOList.add(teamUserVO);
        }
        return teamUserVOList;

    }

    @Override
    public boolean updateTeam(TeamUpdateRequest teamUpdateRequest, User loginUser) {
        //首先检查teamUpdateRequest是否为空，如果为空则抛出BusinessException
        if (teamUpdateRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //然后获取请求中的团队ID，如果ID为空或者小于等于0，也抛出BusinessException，
        // 错误码同样是ErrorCode.PARAMS_ERROR。
        Long id=teamUpdateRequest.getId();
        if (id==null||id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //使用团队ID查询数据库中是否存在该团队，如果查询结果为空，则抛出BusinessException
        Team oldTeam=this.getById(id);
        if (oldTeam==null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"队伍不存在");
        }

//        System.out.println("num1:"+oldTeam.getUserId());
//        System.out.println("num2:"+loginUser.getId());

        //只有管理员或者队伍的创建者可以修改
        if (!Objects.equals(oldTeam.getUserId(), loginUser.getId()) &&!userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //获取队伍状态，并检查是否为加密状态，如果是，则检查是否设置了密码，
        // 如果没有设置密码，则抛出BusinessException异常
        TeamStatusEnum statusEnum=TeamStatusEnum.getEnumByValue(teamUpdateRequest.getStatus());
        if (statusEnum.equals(TeamStatusEnum.SECRET)){
            if (StringUtils.isBlank(teamUpdateRequest.getPassword())){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"加密房间必须要设置密码");
            }
        }
        //创建一个新的Team对象,并将teamUpdateRequest中的属性复制到updateTeam中。
        Team updateTeam=new Team();
        BeanUtils.copyProperties(teamUpdateRequest,updateTeam);
        //使用updateById方法更新队伍信息,并返回更新结果
        return this.updateById(updateTeam);
    }

    /**
     * update队伍更新
     * @param
     * @param loginUser
     * @retun
     * */
    @Override
    public boolean joinTeam(TeamJoinRequest teamJoinRequest, User loginUser) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long teamId = teamJoinRequest.getTeamId();
        if (teamId == null || teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = this.getById(teamId);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在");
        }
        Date expireTime = team.getExpireTime();
        if (expireTime != null && expireTime.before(new Date())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍已过期");
        }
        Integer status = team.getStatus();
        TeamStatusEnum teamStatusEnum = TeamStatusEnum.getEnumByValue(status);
        if (TeamStatusEnum.PRIVATE.equals(teamStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "禁止加入私有队伍");
        }
        String password = teamJoinRequest.getPassword();
        if (TeamStatusEnum.SECRET.equals(teamStatusEnum)) {
            if (StringUtils.isBlank(password) || !password.equals(team.getPassword())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
            }
        }


        //该用户已加入的队伍数量
        long userId = loginUser.getId();
        // 只有一个线程能获取到锁
        RLock lock = redissonClient.getLock("yupao:join_team");
        try {
            while(true){
                if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)){
                    System.out.println("getLock: " + Thread.currentThread().getId());
                    //创建了一个QueryWrapper对象，用于构建数据库查询条件。
                    // QueryWrapper是MyBatis-Plus框架中的一个类，用于生成SQL查询语句。
                    QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
                    //long num=userTeamService.count(userTeamQueryWrapper);
                    //设置了查询条件，用于查询UserTeam表中userId字段等于当前登录用户ID的记录
                    userTeamQueryWrapper.eq("userId", userId);
                    //调用了userTeamService的count方法，使用前面构建的查询条件来统计满足条件的记录数，
                    // 即用户已经加入的队伍数量。
                    long hasJoinNum = userTeamService.count(userTeamQueryWrapper);
                    //如果用户已经加入的队伍数量大于5，则抛出一个BusinessException异常
                    if (hasJoinNum > 5) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "最多创建和加入5个队伍");
                    }
                    //不能重复加入已加入的队伍
                    userTeamQueryWrapper = new QueryWrapper<>();
                    userTeamQueryWrapper.eq("userId", userId);
                    userTeamQueryWrapper.eq("teamId", teamId);
                    long hasUserJoinTeam = userTeamService.count(userTeamQueryWrapper);
                    if (hasUserJoinTeam > 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户已加入该队伍");
                    }
                    //已加入队伍的人数
                    long teamHasJoinNum = this.countTeamUserByTeamId(teamId);
                    if (teamHasJoinNum >= team.getMaxNum()) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍已满");
                    }
                    //加入,修改队伍信息
                    UserTeam userTeam = new UserTeam();
                    userTeam.setUserId(userId);
                    userTeam.setTeamId(teamId);
                    userTeam.setJoinTime(new Date());
                    return userTeamService.save(userTeam);
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
            return false;
        } finally {
            // 只能释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean quitTeam(TeamQuitRequest teamQuitRequest, User loginUser){
        // 如果请求对象为空，抛出参数错误异常
        if (teamQuitRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 从请求对象中获取要退出的团队ID
        Long teamId=teamQuitRequest.getTeamId();
        // 如果团队ID为空或小于等于0，抛出空值错误异常
        if (teamId==null || teamId<=0){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 根据团队ID查询团队信息
        Team team=this.getById(teamId);
        // 如果团队不存在，抛出空值错误异常，并附上错误信息
        if (team==null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"队伍不存在");
        }
        // 获取登录用户的ID
        long userId=loginUser.getId();
        // 创建一个UserTeam对象，用于查询用户与团队的关系
        UserTeam queryUserTeam=new UserTeam();
        queryUserTeam.setTeamId(teamId);
        queryUserTeam.setUserId(userId);
        // 创建查询包装器
        QueryWrapper<UserTeam> queryWrapper=new QueryWrapper<>(queryUserTeam);
        // 查询用户是否在团队中
        long count=userTeamService.count(queryWrapper);
        // 如果用户不在团队中，抛出参数错误异常，并附上错误信息
        if (count==0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"未加入队伍");
        }
        long teamHasJoinNum = this.countTeamUserByTeamId(teamId);
        //队伍只剩一人,解散
        if (teamHasJoinNum==1){
            //删除队伍
            this.removeById(teamId);
        } else {
            //队伍至少还剩两人
            //是队长
            if (team.getUserId()==userId){
                //把队伍转移给最早加入的用户
                //1、查询已加入队伍的所有用户和加入时间
                QueryWrapper<UserTeam> userTeamQueryWrapper=new QueryWrapper<>();
                userTeamQueryWrapper.eq("teamId",teamId);
                userTeamQueryWrapper.last("order by id asc limit 2");
                List<UserTeam> userTeamList=userTeamService.list(userTeamQueryWrapper);
                if (CollectionUtils.isEmpty(userTeamList)||userTeamList.size()<=1){
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR);
                }
                UserTeam nextUserTeam=userTeamList.get(1);
                Long nextTeamLeaderId=nextUserTeam.getUserId();
                //更新当前队伍的队长
                Team updateTeam=new Team();
                updateTeam.setId(teamId);
                updateTeam.setUserId(nextTeamLeaderId);
                boolean result=this.updateById(updateTeam);
                if (!result){
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新队伍失败");
                }
            }
        }
        //移除失败
        return userTeamService.remove(queryWrapper);



    }

    /**
     * 解散队伍
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTeam(long id,User loginUser){
        // 校验队伍是否存在
        Team team = getTeamById(id);
        long teamId = team.getId();
        //long a1=team.getUserId();
        //long a2=loginUser.getId();
        // 校验你是不是队伍的队长
        if (!Objects.equals(team.getUserId(), loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无访问权限");
        }
        // 移除所有加入队伍的关联信息
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        userTeamQueryWrapper.eq("teamId", teamId);
        boolean result = userTeamService.remove(userTeamQueryWrapper);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除队伍关联信息失败");
        }
        // 删除队伍
        return this.removeById(teamId);

    }

    /**
     * 根据 id 获取队伍信息
     *
     * @param teamId
     * @return
     */
    private Team getTeamById(Long teamId) {
        if (teamId == null || teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = this.getById(teamId);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在");
        }
        return team;
    }

    /**
     * 获取某队伍当前人数
     *
     * @param teamId
     * @return
     */
    private long countTeamUserByTeamId(long teamId) {
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        userTeamQueryWrapper.eq("teamId", teamId);
        return userTeamService.count(userTeamQueryWrapper);
    }
}




























